/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.chinalwb.are.styles;

import com.chinalwb.are.ListStateBean;
import com.chinalwb.are.OnItemClickListener;
import com.chinalwb.are.ResourceTable;
import com.chinalwb.are.ViewScrollListener;
import com.chinalwb.are.utils.FindUtils;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * 可滑动样式类
 *
 * @author hal
 * @since 2021/06/22
 */
public class ListComponent extends DirectionalLayout {
    private ListProvider listProvider;
    private ListContainer listContainer;
    private OnItemClickListener onItemClickListener;
    private ViewScrollListener viewScrollListener;
    private List<ListStateBean> iconList;

    public ListComponent(Context context) {
        this(context, null);
    }

    public ListComponent(Context context, AttrSet attrSet) {
        this(context, attrSet, "");
    }

    public ListComponent(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        initView(context);
    }

    public void setViewScrollListener(ViewScrollListener viewScrollListener) {
        this.viewScrollListener = viewScrollListener;
    }

    /**
     * 滑动到指定位置
     *
     * @param position 位置
     */
    public void scrollPosition(int position) {
        if (position > 0) {
            // 因为直接调用scrollTo 会发生回弹，我也很难受！！
            listContainer.scrollTo(AttrHelper.vp2px(40, getContext()) * iconList.size(), 0);
        } else {
            listContainer.scrollTo(position);
        }
    }

    private void initView(Context context) {
        List<ListStateBean> list = new ArrayList<>();
        Component component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_list_con, this, true);
        listContainer = FindUtils.findListById(component, ResourceTable.Id_list);
        listContainer.setOrientation(Component.HORIZONTAL);
        listProvider = new ListProvider(list);
        listContainer.setItemProvider(listProvider);
        listContainer.setItemClickedListener((listContainer, component12, position, l) -> {
            if (onItemClickListener != null) {
                ListStateBean item = listProvider.getItem(position);
                if (!item.isSizeOrColor()) {
                    item.setIsSelected(!item.getIsSelected());
                    listProvider.notifyDataSetItemChanged(position);
                }
                onItemClickListener.itemClick(item, position);
            }
        });
        listContainer.addScrolledListener((component1, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            int lastVisibleItemPosition = listContainer.getLastVisibleItemPosition();
            if (viewScrollListener != null) {
                viewScrollListener.scrolled(lastVisibleItemPosition);
            }
        });
    }

    /**
     * 设置数据
     *
     * @param context  context
     * @param iconList iconList
     */
    public void setData(Context context, List<ListStateBean> iconList) {
        this.iconList = iconList;
        context.getUITaskDispatcher().delayDispatch(() -> {
            listProvider.iconList.addAll(iconList);
            listProvider.notifyDataChanged();
        }, 100);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }


    private static class ListProvider extends BaseItemProvider {
        private final List<ListStateBean> iconList;

        ListProvider(List<ListStateBean> list) {
            this.iconList = list;
        }

        @Override
        public int getCount() {
            return iconList.size();
        }

        @Override
        public ListStateBean getItem(int position) {
            return iconList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
            ViewHolder viewHolder = null;
            if (component == null) {
                component = LayoutScatter.getInstance(componentContainer.getContext()).parse(
                        ResourceTable.Layout_list_con_item, componentContainer, false);
                viewHolder = new ViewHolder(component);
                component.setTag(viewHolder);
            } else {
                Object tag = component.getTag();
                if (tag instanceof ViewHolder) {
                    viewHolder = (ViewHolder) tag;
                }
            }
            ShapeElement shapeElement = new ShapeElement();
            shapeElement.setRgbColor(RgbColor.fromArgbInt(iconList.get(position).getIsSelected() ?
                    Color.RED.getValue() : Color.TRANSPARENT.getValue()));
            viewHolder.img.setPixelMap(iconList.get(position).getIcon());
            viewHolder.item.setBackground(shapeElement);
            return component;
        }
    }

    /**
     * viewholder
     */
    public static class ViewHolder {
        /**
         * img
         */
        public Image img;
        /**
         * item
         */
        public Component item;

        public ViewHolder(Component componentContainer) {
            img = FindUtils.findImageById(componentContainer, ResourceTable.Id_img);
            item = componentContainer.findComponentById(ResourceTable.Id_item);
        }
    }
}
